/* eslint-disable no-plusplus, function-paren-newline */
import React, { Component } from 'react';
import { Form, Row, Col, Input, Button, Icon, Select, DatePicker, Modal, message } from 'antd';
import moment from 'moment';
import * as config from '../../../utils/config';
import styles from './FastFilter.less';
import * as commonFunc from '../commonFunc';

const FormItem = Form.Item;
const { Option } = Select;
let uuid = 0;

const AdvancedSearchForm = Form.create()((props) => {
  const {
    handleSearch, handleOk, handleCancel, handleFields,
    handeToggle, handleAdd, handleSave, handleReset, handleCloseTag,
  } = props;
  const {
    firstColumns, visible, confirmLoading, formItemLayout, form, expand, activeTagId, userinfo, sType,
  } = props;
  const { getFieldDecorator } = form;
  return (
    <Form
      className={styles.advForm}
      onSubmit={handleSearch}
    >
      <Row className={expand ? styles.advRowActive : styles.advRow}>
        {handleFields(firstColumns, form)}
        <button className={styles.advTogIcon} onClick={handeToggle}>
          <Icon type={expand ? 'up' : 'down'} />
        </button>
        {
            (activeTagId === 'default' || (sType === 'common' && userinfo.sType !== 'sysadmin')) ?
              <Col span={24} style={{ display: expand ? 'block' : 'none' }}>
                <Col span={20}>
                  <div className={styles.advButton}>
                    <Button
                      type="primary"
                      onClick={handleAdd}
                    >
                      <Icon type="plus" /> 添加条件
                    </Button>
                  </div>
                </Col>
                <Col span={4}>
                  <div className={styles.advButton}>
                    <Button onClick={handleSave}>
                      保存
                    </Button>
                  </div>
                </Col>
              </Col>
              :
              <Col span={24} style={{ display: expand ? 'block' : 'none' }}>
                <Col span={16}>
                  <div className={styles.advButton}>
                    <Button
                      type="primary"
                      onClick={handleAdd}
                    >
                      <Icon type="plus" /> 添加条件
                    </Button>
                  </div>
                </Col>
                <Col span={4}>
                  <div className={styles.advButton}>
                    <Button onClick={handleSave}>
                      保存
                    </Button>
                  </div>
                </Col>
                <Col span={4}>
                  <div className={styles.advButton}>
                    <Button onClick={handleCloseTag}>
                      删除
                    </Button>
                  </div>
                </Col>
              </Col>
          }
      </Row>
      <Col span={24} className={styles.advCol}>
        <Button type="primary" htmlType="submit">搜索</Button>
        <Button type="primary" style={{ marginLeft: 8 }} onClick={handleReset}>
            清空
        </Button>
      </Col>
      <Modal
        visible={visible}
        title="过滤方案另存"
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
        confirmLoading={confirmLoading}
      >
        <Form>
          <FormItem
            {...formItemLayout}
            label="方案名称"
            hasFeedback
          >
            {getFieldDecorator('sName', {
                rules: [{
                  required: visible, message: '请输入方案名称',
                }],
              })(<Input />)}
          </FormItem>
        </Form>
      </Modal>
    </Form>
  );
});

class FastFilterComponent extends Component {
  constructor(props) {
    super(props);
    this.seaJudge = config.seaJudge; /* 判断条件 */
    this.state = {
      componentName: props.componentName,
      fastUrl: `${config.server_host}syssearch/getSyssearchData/${props.formId}?sModelsId=${props.formId}`, /* 获取快捷查找方案 */
      sGrd: '', /* 表格 */
      expand: false, /* 快捷过滤显示与否 */
      firstColumns: [], /* 搜索字段 */
      visible: false, /* 过滤保存方案另存弹窗是否显示 */
      fData: [], /* 过滤模板 */
      confirmLoading: false, /* 新增弹窗加载 */
      activeTagId: 'default', /* 当前选中的快捷过滤方案 */
      sType: 'common', /* 快捷过滤是什么类型的 */
      fastConfig: {}, /* 过滤条件配置 */
      sTableId: props.sTabId,
      formId: props.formId,
      userinfo: props.app.userinfo, /* 用户信息 */
      gdsformconst: props.gdsformconst,
      systemData: props.app.systemData, /* 系统参数 */
      dateFormat: commonFunc.getDateFormat(props.app.systemData),
    };
    this.fastFlag = ''; /* 判断是否增加快捷过滤 */
    this.fastbFilter = []; /* 快捷过滤方案条件 */
  }

  componentWillMount() {
    const { fastUrl, componentName } = this.state;
    const { sTabId, dispatch } = this.props;
    dispatch({ type: 'content/getUrlData', payload: { url: fastUrl, sTabId, componentName } });
  }

  componentWillReceiveProps(nextProps) {
    const { systemData } = nextProps.app;
    const dateFormat = commonFunc.getDateFormat(systemData);
    this.setState({ dateFormat });
    const { dataList } = nextProps.content;
    const {
      sDataListTabId, componentName, urlData, loading, fastFlag,
    } = dataList;
    if (nextProps.sTabId === sDataListTabId &&
      this.state.componentName === componentName) {
      if (loading) {
        this.setState({ loading: true });
        return;
      }
      const { gdsconfigformslave } = nextProps.masterConfig;
      const firstColumns = commonFunc.getFastConfig(gdsconfigformslave);
      /* 获取快捷过滤方案 */
      const fDataNew = urlData;
      let { fData } = this.state; /* 快捷方案 */
      const { activeTagId } = this.state;
      if (fastFlag === 'add') {
        const { sType } = this.state.userinfo;
        if (sType !== 'sysadmin') {
          fDataNew[0].sType = 'uncommon';
          this.setState({ sType: 'uncommon' });
        } else {
          fDataNew[0].sType = 'common';
          this.setState({ sType: 'common' });
        }
        fData.push(fDataNew[0]);
        const { sId } = fDataNew[0];
        this.setState({ activeTagId: sId });
      } else if (fastFlag === 'del') {
        const fDataDel = fData.filter(item => item.sId === fDataNew[0].sId);
        const Index = fData.indexOf(fDataDel[0]);
        fData.splice(Index, 1);
        if (fData.length > 0 && activeTagId !== '' && activeTagId === fDataDel[0].sId) {
          this.setState({
            activeTagId: fData[fData.length - 1].sId,
            expand: true,
            sType: fData[fData.length - 1].sType,
          });
          uuid = this.fastbFilter.length - 1;
          const bFilter = JSON.parse(fData[fData.length - 1].sCondition); /* ;字符转对象 */
          this.handlebFilterConversion(bFilter);
          this.props.onSaveFilter(bFilter);
        } else if (fData.length === 0) {
          this.setState({
            activeTagId: 'default',
            expand: false,
            sType: 'common',
          });
          this.form.resetFields();
        }
      } else if (this.state.fData.length === 0) {
        fData = fDataNew;
      }
      this.fastFlag = ''; /* 增加或删除方案的标志 */
      this.setState({ firstColumns, fData, fastConfig: { sDataListTabId, componentName } });
    }
    /*
    const fastConfig = nextProps.mergeTable.tableConfig;
    const { configType, componentName, sDataListTabId } = fastConfig; /!* 快捷列表及相对应的标签 *!/
    if (this.state.sTabId === sDataListTabId && this.state.sTabId === nextProps.app.sTabId
      && configType === 'fast' && this.state.componentName === componentName) {
      const isRefresh = fastConfig.isRefresh || false;
      if (this.state.firstColumns.length > 0 && isRefresh) {
        /!* 有可能快捷过滤不显示 *!/
        this.form.resetFields();
        this.setState({
          activeTagId: '',
          expand: false,
        });
      } /!* 点击工具栏刷新，条件清空 *!/
      if (Object.keys(this.state.firstColumns).length === 0) {
        const { firstColumns, sId, sParentId } = fastConfig; /!* 搜索字段列表以及过滤地址 *!/
        this.setState({ sGrd: componentName, firstColumns, sId, sParentId, fastConfig });
      }
      /!* 获取快捷过滤方案 *!/
      const fDataNew = fastConfig.fData;
      let fData = this.state.fData; /!* 快捷方案 *!/
      if (this.fastFlag === 'add') {
        fData.push(fDataNew[0]);
        const { sId } = fDataNew[0];
        this.setState({ activeTagId: sId });
      } else if (this.fastFlag === 'del') {
        const fDataDel = fData.filter(item => item.sId === fDataNew[0].sId);
        const Index = fData.indexOf(fDataDel[0]);
        fData.splice(Index, 1);
      } else if (this.state.fData.length === 0) {
        fData = fDataNew;
      }
      this.setState({
        fData,
      });
      this.fastFlag = ''; /!* 增加或删除方案的标志 *!/
    } */
    /* 翻页时，收缩条件回收 */
    // if (Object.keys(dataList).length > 0) {
    //   const { pages } = dataList;
    //   if (pages !== undefined) {
    //     const { pageNum } = pages;
    //     if (pageNum > 1) {
    //       this.setState({ expand: false });
    //     }
    //   }
    // }
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { dataList } = nextProps.content;
    const { sDataListTabId, componentName } = dataList;
    if (nextState.expand !== this.state.expand) return true;
    if (nextState.visible !== this.state.visible) return true;
    if (nextState.activeTagId !== this.state.activeTagId) return true;
    return nextProps.sTabId === sDataListTabId && nextState.componentName === componentName;
  }

  handeToggle = () => {
    /* 是否展开多出的条件内容 */
    const { expand } = this.state;
    this.setState({ expand: !expand });
  };

  handleAdd = () => {
    /* 添加条件 */
    uuid++;
    const { form } = this;
    const keys = form.getFieldValue('keys');
    if (keys.length === 10) {
      const { gdsformconst } = this.state;
      const maxFilter = gdsformconst.filter(item => (item.sName === 'maxFilter'))[0].showName;
      return message.warning(maxFilter);
    } else {
      const nextKeys = keys.concat(uuid);
      form.setFieldsValue({
        keys: nextKeys,
      });
    }
  };

  handleRemove = (k) => {
    /* 移除添加条件 */
    const { form } = this;
    const keys = form.getFieldValue('keys');
    if (keys.length === 1) {
      return;
    }
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };

  handleSave = () => {
    /* 保存快捷过滤模板 */
    const { fData } = this.state;
    if (fData.length === config.maxTabSize) {
      message.error('过滤方案已超过限制，无法新增！');
    } else {
      this.setState({
        visible: true,
      });
    }
  };

  handleOk = (e) => {
    /* 保存方案 */
    e.preventDefault();
    const { form } = this;
    const values = form.getFieldsValue();
    const { sName } = values;
    if (sName === undefined || sName === '') {
      form.validateFields();
      return;
    }
    this.setState({
      confirmLoading: true, /* 点击确定, 加载转圈 */
    });
    setTimeout(() => {
      form.setFieldsValue({
        sName: '',
      });
      this.setState({
        visible: false,
        confirmLoading: false,
      });
    }, 1000);
    const {
      sTableId, formId, fastConfig, componentName,
    } = this.state; /* 表Id 以及 窗体Id */
    const { keys } = values;
    const sCondition = []; /* 数据筛选条件 */
    keys.map((k) => {
      const firstColType = values[`first-${k}`].substring(0, 1);
      const time = (firstColType === 't' && values[`third-${k}-${firstColType}`] !== null)
        ? values[`third-${k}-${firstColType}`].format('YYYY-MM-DD') : ''; /* 时间控件值判断 */
      sCondition.push({
        bFilterName: values[`first-${k}`],
        bFilterCondition: values[`second-${k}`],
        bFilterValue: firstColType !== 't' ? values[`third-${k}-${firstColType}`] : time,
      });
      return true;
    });
    const value = {
      sFormId: formId,
      sTableId,
      sCondition,
      sName: values.sName,
    };
    const addUrl = `${config.server_host}syssearch/addSyssearch?sModelsId=${formId}`;
    const { dispatch } = this.props;
    const fastFlag = 'add'; /* 保存后快捷方案设为'add'，用于后面的判断 */
    dispatch({
      type: 'fastFilter/addFastData',
      payload: {
        value, addUrl, fastConfig, fastFlag, componentName, sTableId,
      },
    });
  };

  handleCloseTag = (e) => {
    /* 删除快捷过滤模板 */
    e.preventDefault(); /* 防止动画删除 */
    const { formId, fastConfig, activeTagId } = this.state;
    const { dispatch } = this.props;
    const delUrl = `${config.server_host}syssearch/deleteSyssearch/${formId}/${activeTagId}?sModelsId=${formId}`;
    const fastFlag = 'del';
    dispatch({ type: 'fastFilter/delFastData', payload: { delUrl, fConfig: fastConfig, fastFlag } });
  };

  handleReset = () => {
    /* 清空搜索条件 */
    uuid = 0;
    this.form.resetFields();
    if (this.state.activeTagId !== '') {
      const { firstColumns } = this.state;
      const firstKey = firstColumns[0].key;
      let firstColType = firstKey.substring(0, 1);
      /* 如果sName为pro_打头则为存储过程查询条件，此处特殊处理 */
      if (firstColType === 'p') {
        firstColType = 's';
      }
      const secondCon = this.seaJudge[firstColType]; /* 搜索条件 */
      const { setFieldsValue } = this.form;
      setFieldsValue({
        'first-0': firstKey,
        'second-0': secondCon[0].key,
      });
      this.setState({ activeTagId: 'default', expand: false });
    }
    this.props.onSaveFilter([]);
  };

  handleFirstChange = (value, secondValue) => {
    /* 第二控件更改，再第一控件更改的情况，第二控件默认值设置 */
    let firstColType = value.substring(0, 1);
    /* 如果sName为pro_打头则为存储过程查询条件，此处特殊处理 */
    if (firstColType === 'p') {
      firstColType = 's';
    }
    const secondCon = this.seaJudge[firstColType];
    const { setFieldsValue } = this.form;
    setFieldsValue({
      [secondValue]: secondCon[0].key,
    });
  };

  handleSecondChange = (value, thirdValue) => {
    /* 时间控件是否显示判断 */
    const timeFlag = !!(value === 'day' || value === 'month' || value === 'week');
    const { resetFields } = this.form;
    if (timeFlag) resetFields([thirdValue]);
  };

  handleSearch = (e) => {
    /* 点击搜索取值 */
    e.preventDefault();
    const { form } = this;
    form.validateFields({ force: true }, (err, values) => {
      if (!err) {
        const { keys } = values;
        const aFilter = []; /* 数据筛选条件 */
        keys.map((k) => {
          let firstColType = values[`first-${k}`].substring(0, 1);
          /* 如果sName为pro_打头则为存储过程查询条件，此处特殊处理 */
          if (firstColType === 'p') {
            firstColType = 's';
          }
          const time = (firstColType === 't' && values[`third-${k}-${firstColType}`] !== null)
            ? values[`third-${k}-${firstColType}`].format('YYYY-MM-DD') : ''; /* 时间控件值判断 */
          aFilter.push({
            bFilterName: values[`first-${k}`],
            bFilterCondition: values[`second-${k}`],
            bFilterValue: firstColType !== 't' ? values[`third-${k}-${firstColType}`] : time,
          });
          return true;
        });
        this.props.onSaveFilter(aFilter);
      }
    });
  };

  handleSelectChange = (value, option) => {
    /* 选择方案，进行筛选 */
    if (value !== 'default') {
      const { opt } = option.props;
      this.setState({
        activeTagId: opt.sId,
        sType: opt.sType,
      });
      const bFilter = JSON.parse(opt.sCondition); /* ;字符转对象 */
      if (bFilter.length === 1) {
        this.setState({ expand: false });
      } else {
        this.setState({ expand: true });
      }
      this.fastbFilter = bFilter; /* 快捷查询条件 */
      uuid = this.fastbFilter.length - 1;
      this.handlebFilterConversion(bFilter);
      /* 显示条件数 */
      this.props.onSaveFilter(bFilter);
    } else {
      this.handleReset();
    }
  };

  /* 快捷方案条件转化控件展示 */
  handlebFilterConversion(bFilter) {
    const { form } = this;
    const keys = [];
    const { dateFormat } = this.state; /* 日期控件显示格式 */
    bFilter.map((child, i) => {
      const firstColType = child.bFilterName.substring(0, 1); /* 搜索字段类型 */
      const thirdValue = firstColType === 'b' ? '1' : firstColType === 't' ? null : '';
      form.getFieldDecorator(`first-${i}`, { initialValue: '' });
      form.getFieldDecorator(`second-${i}`, { initialValue: '' });
      form.getFieldDecorator(`third-${i}-${firstColType}`, { initialValue: thirdValue });
      form.setFieldsValue({
        [`first-${i}`]: child.bFilterName,
        [`second-${i}`]: child.bFilterCondition,
        [`third-${i}-${firstColType}`]: firstColType === 't'
          ? child.bFilterValue === ''
            ? null
            : moment(`${child.bFilterValue}`, dateFormat)
          : child.bFilterValue,
      });
      keys.push(i);
      return keys;
    });
    form.setFieldsValue({
      keys,
    });
  }

  handleCancel = () => {
    /* 关闭弹窗 */
    const { form } = this;
    form.setFieldsValue({
      sName: '',
    });
    this.setState({ visible: false });
  };

  handleFields = (firstColumns, form) => {
    /* 默认快捷过滤 */
    const count = this.state.expand ? 10 : 1;
    this.form = form;
    const { getFieldDecorator, getFieldValue } = form;
    getFieldDecorator('keys', { initialValue: [0] });
    const keys = getFieldValue('keys'); /* 代表一行下拉框的唯一键 */
    const children = keys.map((k) => {
      /* 字段列表 */
      const firstKey = getFieldValue(`first-${k}`) || firstColumns[0].key; /* 默认搜索字段 */
      let firstColType = firstKey.substring(0, 1); /* 搜索字段类型 */
      /* 如果sName为pro_打头则为存储过程查询条件，此处特殊处理 */
      if (firstColType === 'p') {
        firstColType = 's';
      }
      const columnOptions = firstColumns.map(child =>
        <Option key={child.key}>{child.value}</Option>);
      const secondCon = this.seaJudge[firstColType]; /* 搜索条件 */
      const conOptions = secondCon.map(child => <Option key={child.key}>{child.value}</Option>);
      const conKey = getFieldValue(`second-${k}`) || secondCon[0].key; /* 默认搜索条件值 */
      const secondKey = getFieldValue(`second-${k}`) || secondCon[0].key;
      const timeFlag = secondKey === 'day' || secondKey === 'month' || secondKey === 'week';
      const { dateFormat } = this.state; /* 日期控件显示格式 */
      const thirdRules = {
        initialValue: firstColType === 'b' ? '1' : firstColType === 't' ? null : '',
        rules: [{ required: !timeFlag, message: '请选择或输入内容!' }],
      };
      return (
        <Col span={24} key={k} style={{ display: k < count ? 'block' : 'none' }}>
          <Col span={8}>
            <FormItem className={styles.advFormItem}>
              {
                getFieldDecorator(`first-${k}`, {
                  initialValue: `${firstKey}`,
                })(
                  <Select
                    onChange={value => this.handleFirstChange(value, `second-${k}`)}
                  >
                    {columnOptions}
                  </Select>)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem className={styles.advFormItem}>
              {
                getFieldDecorator(`second-${k}`, {
                  initialValue: `${conKey}`,
                })(
                  <Select
                    onChange={value => this.handleSecondChange(value, `third-${k}-${firstColType}`)}
                  >
                    {conOptions}
                  </Select>)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem className={styles.advFormItem}>
              {
                getFieldDecorator(`third-${k}-${firstColType}`, thirdRules)(firstColType === 'b' ?
                  <Select className={styles.advInput}>
                    <Option value="1">是</Option>
                    <Option value="0">否</Option>
                  </Select>
                    : firstColType === 't' ?
                      <DatePicker
                        format={dateFormat}
                        className={styles.advInput}
                        disabled={timeFlag}
                      />
                    :
                      <Input placeholder="请输入你要搜索的内容" className={styles.advInput} />)
              }
              {k > 0 ? (
                <div className={styles.advDelectIcon}>
                  <Icon
                    type="minus-circle-o"
                    onClick={() => this.handleRemove(k)}
                  />
                </div>
              ) : null}
            </FormItem>
          </Col>
        </Col>
      );
    });
    return children;
  };

  render() {
    const { firstColumns, activeTagId, fData } = this.state;
    /* 搜索字段, 过滤保存方案另存弹窗是否显示, 快捷过滤方案, 新增弹窗加载 */
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    }; /* 过滤另存方案界面显示 */
    return (
      <div>
        {
          firstColumns.length > 0 ?
            <div>
              <div className={styles.fastFilter}>
                <Select
                  style={{ width: '14%' }}
                  className={styles.fastSelect}
                  onSelect={this.handleSelectChange}
                  value={activeTagId}
                >
                  <Option key="default">快捷过滤-方案</Option>
                  { fData.map(opt =>
                    (
                      <Option key={opt.sId} opt={opt}>
                        {opt.sName}
                      </Option>
                    ))
                  }
                </Select>
                <AdvancedSearchForm
                  {...this.state}
                  handleSearch={this.handleSearch}
                  handleFields={this.handleFields}
                  handeToggle={this.handeToggle}
                  handleAdd={this.handleAdd}
                  handleSave={this.handleSave}
                  handleReset={this.handleReset}
                  formItemLayout={formItemLayout}
                  handleOk={this.handleOk}
                  handleCancel={this.handleCancel}
                  handleCloseTag={this.handleCloseTag}
                />
              </div>
            </div>
            : ''
        }
      </div>
    );
  }
}

export default FastFilterComponent;
